import {createRouter, createWebHistory} from 'vue-router';
import store from '../store/user.js'; // 引入 store 来获取用户角色

const routes = [
    {
        path: '/',
        redirect: '/home',
    },
    {
        path: '/home',
        name: 'Home',
        component: () => import('../views/Home.vue'),
        meta: {requiresAuth: true}, // 需要身份验证
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('../views/Login.vue'),
    },
    {
        path: '/register',
        name: 'Register',
        component: () => import('../views/Register.vue'),
    },
    {
        path: '/order',
        name: 'Order',
        component: () => import('../views/Order.vue'),
        meta: { requiresAuth: true}, // 仅 'user' 角色可以访问
    },
    {
        path: '/address',
        name: 'Address',
        component: () => import('../views/Address.vue'),
        meta: {requiresAuth: true}, // 仅 'user' 角色可以访问
    },
    {
        path: '/profile',
        name: 'Profile',
        component: () => import('../views/Profile.vue'),
        meta: {requiresAuth: true}, // 仅 'user' 角色可以访问
    },
    {
        path: '/scan',
        name: 'Scan',
        component: () => import('../views/Scan.vue'),
        meta: {requiresAuth: true, role: 'courier'}, // 仅 'courier' 角色可以访问
    },
    {
        path: '/order/update',
        name: 'OrderUpdate',
        component: () => import('../views/OrderUpdate.vue'),
        meta: {requiresAuth: true, role: 'courier'}, // 仅 'courier' 角色可以访问
    },
];

const router = createRouter({
    history: createWebHistory(), // 使用 createWebHistory 代替 createMemoryHistory
    routes,
});

// 设置路由守卫
router.beforeEach((to, from, next) => {
    const isLoggedIn = store.getters.isLoggedIn; // 使用 getters 获取登录状态
    const userRole = store.getters.userRole; // 直接获取用户角色
    if (to.meta.requiresAuth && !isLoggedIn) {
        return next({name: 'Login', query: {redirect: to.fullPath}});
    }
    if (to.meta.role && (!isLoggedIn || (userRole !== to.meta.role))) {
        return next({name: 'Home'}); // 如果角色不匹配，重定向到首页
    }
    console.log(`Navigating to: ${to.path}, requiresAuth: ${!!to.meta.requiresAuth}, isLoggedIn: ${isLoggedIn}, userRole: ${userRole}`);
    next(); // 允许访问
});
export default router;